from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
from django.db import DatabaseError
from user.models import User


def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError):
            print('[%s]:%s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response



def jwt_response_payload_handler(token, user=None, request=None, role=None):
    """
    自定义jwt认证成功返回数据
    :token  返回的jwt
    :user   当前登录的用户信息[对象]
    :request 当前本次客户端提交过来的数据
    :role 角色
    """
    if user.first_name:
        name = user.first_name
    else:
        name = user.username
    return {
        'authenticated': 'true',
        'id': user.id,
        "role": role,
        'name': name,
        'username': user.username,
        'email': user.email,
        'token': token,
        'img':str(user.img),
    }



class EmailAuthBackend:
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(email=username)
        except Exception as e:
            user = None
        print(user)
        print(user.check_password(password))
        if user and user.check_password(password):
            return user
        else:
            return None


class PhoneAuthBackend:
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(phone=username)
        except Exception as e:
            user = None
        print(user)
        print(user.check_password(password))
        if user and user.check_password(password):
            return user
        else:
            return None